package com.homson.coreservice.serviceinfrastructure.datasource.repository.account;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.homson.coreservice.servicecommon.co.TransactionAddCO;
import com.homson.coreservice.servicecommon.enumeration.TransTypeEnum;
import com.homson.coreservice.servicecommon.enumeration.ValidStatus;
import com.homson.coreservice.serviceinfrastructure.datasource.mapper.TransactionMapper;
import com.homson.coreservice.serviceinfrastructure.datasource.model.account.TransactionDO;
import com.homson.coreservice.serviceinfrastructure.datasource.repository.BaseRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: homson_leo
 * @contact: hey_超级巨星（Homson_Leo）- 刘泓岑 1196816884@qq.com
 * @time: 2025/10/4 11:00 AM
 **/
@Repository
public class TransactionRepository extends BaseRepository<TransactionMapper, TransactionDO> {
    
    @Resource
    private TransactionMapper transactionMapper;
    
    public void createTransaction(TransactionAddCO transactionAddCO) {
        TransactionDO transactionDO = new TransactionDO();
        transactionDO.setAccountId(transactionAddCO.getAccountId());
        transactionDO.setAmount(transactionAddCO.getAmount());
        transactionDO.setType(TransTypeEnum.of(transactionAddCO.getTransType()).name());
        transactionDO.setDescription(transactionAddCO.getDescription());
        transactionDO.setTransDate(LocalDateTime.now());
        transactionDO.createTime();
        transactionDO.updateTime();
        transactionDO.createTransactionId();
        transactionDO.setStatus(ValidStatus.VALID.name());
        this.save(transactionDO);
    }
    
    public List<TransactionDO> findUserRecentTransactionByPage(List<Long> accountIds,Integer pageNum, Integer pageSize){
        if (Objects.isNull(pageNum) || pageNum < 1) {
            pageNum = 1;
        }
        if (Objects.isNull(pageSize) || pageSize <= 0) {
            pageSize = 10;
        }
        IPage<TransactionDO> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TransactionDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TransactionDO::getAccountId, accountIds)
                .eq(TransactionDO::getStatus, ValidStatus.VALID.name())
                .orderByDesc(TransactionDO::getCreatedAt);
        
        IPage<TransactionDO> transactionDOs = transactionMapper.selectPage(page, wrapper);
        return transactionDOs.getRecords();
    }
}
